package server;

import java.util.ArrayList;

public class PriceSteps {
	
	private ArrayList<PriceStep> list;

	public PriceSteps() {
		
		list = new ArrayList<PriceStep>();
		this.add(0, 0, 1, 0);

	}

	public boolean add (double startPrice, double endPrice, double fixedPrice, double variablePricePercent) {
			
		PriceStep priceStep = new PriceStep(startPrice, endPrice, fixedPrice, variablePricePercent);
		
		if (list.size() <= 1) {
			list.add(priceStep);
			return true;
		}
		
		if (endPrice == 0) {
			endPrice = Double.POSITIVE_INFINITY;
			priceStep.setEndPrice(endPrice);
		}
		
		for (int i = 0; i < list.size(); i++) {
			double sPrice = Double.POSITIVE_INFINITY;
			if (i+1 < list.size()) 
				sPrice = list.get(i+1).getStartPrice();
			
			double ePrice = list.get(i).getEndPrice();
			
			if (startPrice >= ePrice && endPrice <= sPrice) {
				list.add(i+1, priceStep);
				return true;
			}
		}
		
		return false;
	}
	
	public boolean delete(double startPrice, double endPrice) {
		
		for (PriceStep p : list) {
			if (startPrice == p.getStartPrice() && endPrice == p.getEndPrice()) {
				list.remove(p);
				return true;
			}
		}
		
		return false;
	}
	

	@Override
	public String toString() {
		
		String output = "Min_Price Max_Price Fee_Fixed Fee_Variable\n";
		int width = 10;
		
		/*
		for (int i = 0; i < list.size(); i++) {
			PriceStep p = list.get(i);
			if (i == 0) {
				String buffer = padRight(Double.toString(p.getStartPrice()), width) + 
						padRight(Double.toString(p.getEndPrice()), width) + 
						padRight(Double.toString(p.getFixedPrice()), width) + 
						padRight(Double.toString(p.getVariablePricePercent()) + "%", width) + "\n";
				
				AttributedString as = new AttributedString(buffer);
			    as.addAttribute(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
				
			}
			else {
				output += padRight(Double.toString(p.getStartPrice()), width) + 
						padRight(Double.toString(p.getEndPrice()), width) + 
						padRight(Double.toString(p.getFixedPrice()), width) + 
						padRight(Double.toString(p.getVariablePricePercent()) + "%", width) + "\n";
			}
		}
		*/
		
		for (PriceStep p : list) {
			
			String sPrice = Double.toString(p.getStartPrice());
			String ePrice = Double.toString(p.getEndPrice());
			String fPrice = Double.toString(p.getFixedPrice());
			String vPrice = Double.toString(p.getVariablePricePercent());
			
			
			if (Double.isInfinite(p.getEndPrice()) && p.getStartPrice() != 0.0)
				ePrice = "infinity";
			
			output += padRight(sPrice, width) + 
					padRight(ePrice, width) + 
					padRight(fPrice, width) + 
					padRight(vPrice + "%", width) + "\n";
		}
		
		return output;
		
	}

	private static String padRight(String s, int n) {
		return String.format("%1$-" + n + "s", s);
	}

}
